<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, message, Tag, Popconfirm, Spin, Input } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
// API
import { getModifyStockRecordList, doModifyStockRecordAgainst, doModifyStockRecordApproval, doModifyStockRecordDelete } from '#/api/modifyStockRecord'

import { getAdminList, getWarehouseList } from '#/api/common' // 假设存在 getWarehouseList
import { useDebounceFn } from '@vueuse/core'
import Form from './modules/form.vue'
import dayjs from 'dayjs'

import { AntPlusOutlined, AntDeleteOutlined, AntCheckOutlined, AntCloseOutlined } from '@vben/icons'

interface RowType {
  [key: string]: any
}

const params = ref<any>({
  quick_search: '',
})
const selectedRows = ref<RowType[]>([])
const formData = ref<any>({})
// 关键字和加载状态，适配新字段
const keyword = ref({
  create_admin_id: '',
  posted_id: '',
  in_warehouse_id: '',
  out_warehouse_id: '',
})
const fetching = ref({
  create_admin_id: false,
  posted_id: false,
  in_warehouse_id: false,
  out_warehouse_id: false,
})

// 获取ApiSelect选项的函数
const fetchCreateAdminOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.create_admin_id,
    select: true,
  })
  return list.map((item: any) => ({ label: item.realname, value: item.id }))
}

const fetchPostedAdminOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.posted_id,
    select: true,
  })
  return list.map((item: any) => ({ label: item.realname, value: item.id }))
}

const fetchOutWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getWarehouseList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: keyword ? '' : formData.value?.out_warehouse_id,
    select: true,
  })
  return list.map((item: any) => ({ label: `${item.warehouse_code}/${item.warehouse_name}`, value: item.id }))
}

// 获取选中行的ID
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.record_id)
}

// 审核按钮禁用逻辑
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.post_time)
})

// 反审按钮禁用逻辑
const isDisabledAgainst = computed(() => {
  console.log('row', selectedRows.value)
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => !row.post_time)
})

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'record_id',
  order: 'desc',
}

const fetchData = async () => {
  gridApi.reload()
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '调拨单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    { component: 'DatePicker', fieldName: 'record_date', label: '单据日期', operator: '=', componentProps: { showTime: true, format: 'YYYY-MM-DD HH:mm:ss', valueFormat: 'YYYY-MM-DD HH:mm:ss' } },
    {
      component: 'ApiSelect',
      fieldName: 'out_warehouse_id',
      label: '调出仓库',
      operator: '=',
      componentProps: () => ({
        api: fetchOutWarehouseOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.out_warehouse_id = value
        }, 300),
        params: {
          keyword: keyword.value.out_warehouse_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        // mode: 'multiple',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.out_warehouse_id = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'create_admin_id',
      label: '创建人',
      operator: '=',
      componentProps: () => ({
        api: fetchCreateAdminOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.create_admin_id = value
        }, 300),
        params: {
          keyword: keyword.value.create_admin_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        // mode: 'multiple',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.create_admin_id = ''
        },
      }),
    },
    {
      component: 'ApiSelect',
      fieldName: 'posted_id',
      label: '审核人',
      operator: '=',
      componentProps: () => ({
        api: fetchPostedAdminOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.posted_id = value
        }, 300),
        params: {
          keyword: keyword.value.posted_id || undefined,
        },
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        allowClear: true,
        // mode: 'multiple',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          if (open) keyword.value.posted_id = ''
        },
      }),
    },
    {
      component: 'Select',
      fieldName: 'post_time',
      label: '审核状态',
      operator: '=',
      componentProps: {
        options: [
          { label: '全部', value: '' },
          { label: '未审核', value: '0' },
          { label: '已审核', value: '1' },
        ],
        placeholder: '请选择',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
   checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'record_id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: { useKey: true },
  // cellConfig: { height: 60 },
  rowStyle({ row }) {
    if (!row.post_time || Number(row.post_time) === 0) {
      return { color: 'red' }
    }
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'record_sn', width: 150, title: '调仓单号', fixed: 'left' },
    { field: 'create_admin', width: 120, title: '操作人' },
    { field: 'created_at', width: 160, title: '创建时间' },
    { field: 'posted', width: 120, title: '审核人' },
    { field: 'postStatus', width: 100, title: '审核状态', slots: { default: 'postStatus' } },
    {
      field: 'post_time',
      width: 160,
      title: '审核时间',
      formatter: ({ cellValue }) => {
        if (cellValue && Number(cellValue) > 0) {
          return dayjs(Number(cellValue) * 1000).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    { field: 'out_ware_house', width: 150, title: '调出仓库' },
    { field: 'record_date', width: 160, title: '单据日期' },
    { field: 'remark', width: 120, title: '备注' },
    { field: 'operation', fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 120 },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: { pageSize: 20 },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }) => {
        const search = await gridApi.formApi.getFiltersValues()
        const postTimeFilter = search.find((f) => f.fieldName === 'post_time')
        if (postTimeFilter?.value === '1') {
          postTimeFilter.operator = '>='
        }
        const res = await getModifyStockRecordList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          quick_search: params.value.quick_search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })
        return { items: res.list, total: res.total }
      },
    },
    sort: true,
  },
  sortConfig: { defaultSort, remote: true },
  toolbarConfig: { custom: true, export: true, refresh: true, resizable: true, search: true, zoom: true },
  id: 'modify_stock_record_list',
  customConfig: {
    storage: true,
  },
}

// 获取审核状态的颜色和文本
const getPostStatusColor = (postTime: number | string) => {
  return postTime && Number(postTime) > 0 ? 'success' : 'warning'
}
const getPostStatusText = (postTime: number | string) => {
  return postTime && Number(postTime) > 0 ? '已审核' : '未审核'
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})
const debouncedReload = useDebounceFn(gridApi.reload, 1000)

// 导出功能
/*
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    const postTimeFilter = search.find((f) => f.fieldName === 'post_time')
    if (postTimeFilter?.value === '1') {
      postTimeFilter.operator = '>='
    }
    // await exportSendRecordData({ search })
  } catch (error) {
    message.error('导出失败')
  } finally {
    hide()
  }
}
*/

// 事件处理
const handleshowFormData = (row: RowType) => {
  FormModalApi.setData({ info: row }).open()
}

const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})

const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({ content: '删除', duration: 0, key: 'action_process_msg' })
  doModifyStockRecordDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({ content: '删除成功', key: 'action_process_msg' })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({ content: '审核', duration: 0, key: 'action_process_msg' })
  doModifyStockRecordApproval({ ids: getSelectionIds() })
    .then(() => {
      message.success({ content: '审核成功', key: 'action_process_msg' })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }
  const hideLoading = message.loading({ content: '反审', duration: 0, key: 'action_process_msg' })
  doModifyStockRecordAgainst({ ids: getSelectionIds() })
    .then(() => {
      message.success({ content: '反审成功', key: 'action_process_msg' })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleshowFormData({})">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          :disabled="isDisabledApproval"
          title="确认删除"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledApproval">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm :disabled="isDisabledApproval" title="确认审核" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
            <AntCheckOutlined />
            审核
          </Button>
        </Popconfirm>
        <Popconfirm :disabled="isDisabledAgainst" title="确认反审" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
            <AntCloseOutlined />
            反审
          </Button>
        </Popconfirm>
        <!-- <Button class="mr-2" type="primary" @click="handleExport">导出</Button> -->
      </template>
      <template #toolbar-tools>
        <div>
          <Input type="text" placeholder="通过主键模糊搜索" v-model:value="params.quick_search" :allow-clear="true" @input="debouncedReload" />
        </div>
      </template>
      <template #postStatus="{ row }">
        <Tag :color="getPostStatusColor(row.post_time)">
          {{ getPostStatusText(row.post_time) }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button class="mr-2" type="primary" size="small" @click.stop="handleshowFormData(row)">编辑</Button>
      </template>
    </Grid>
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
